package cn.com.bluemoon.daps.model.core.file.excel.listener;

import cn.com.bluemoon.daps.common.exception.DapException;
import cn.com.bluemoon.daps.model.core.file.IndexData;
import cn.com.bluemoon.daps.model.core.file.config.GlobalParserConfig;
import com.alibaba.druid.DbType;
import com.alibaba.excel.context.AnalysisContext;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

;

/**
 * // 有个很重要的点 DataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
 *
 * @author Jarod.Kong
 */
public class IndexDataListener extends BaseDataListener<IndexData> {

    public IndexDataListener(GlobalParserConfig globalParserConfig) {
        super(globalParserConfig);
    }

    private static final HashMap<DbType, String> INDEX_DB_HEADER = new HashMap<DbType, String>(6) {{
        put(DbType.mysql, generateHeadNameStr(Arrays.asList("序号", "表英文名", "字段列表", "索引名", "索引描述", "索引类型", "索引方法")));
        put(DbType.postgresql, generateHeadNameStr(Arrays.asList("序号", "表英文名", "字段列表", "索引名", "索引描述", "索引类型", "索引方法")));
        put(DbType.hive, generateHeadNameStr(Collections.emptyList()));
    }};

    /**
     * @return 获取数据库对应的表头信息
     */
    @Override
    protected Map<DbType, String> getDbTypeExcelStandardHeader() {
        return INDEX_DB_HEADER;
    }


    @Override
    public void rowDataValidate0(IndexData data, AnalysisContext context) {
        String dataKey = generateDataLowCaseKey(data.getTableName(), data.getIndexName());
        data.setKey(dataKey);
        boolean preT = checkExcelRepeatMap.contains(data.getKey());
        if (preT) {
            data.getErrorMsgs().add("表索引名重复");
            data.setFail(true);
            noValidExcelDataCollector.add(data);
        }
    }
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        DapException dapException = exception instanceof DapException ? ((DapException) exception) : null;
        if (dapException != null) {
            throw new DapException(dapException.getMessage());
        }
        throw exception;
    }
}